package com.ruoyi.coin.utils;

import com.ruoyi.coin.enums.OklinkChainEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.blade.Func;
import com.ruoyi.common.utils.blade.tool.DateUtil;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.utils.Numeric;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CoinUtils {


    //黑名单列表
    public static List<String> blackTokenlist = new ArrayList<>();

    /**
     * 获取开始日期
     *
     * @param publishAt
     * @param hourKlineCou
     * @return
     */
    public static Date geOpenDate(Long publishAt, Integer hourKlineCou) {
        Date openTime = null;
        if (Func.isEmpty(publishAt)) {
            if (hourKlineCou < 5) {
                openTime = DateUtil.now();
            } else {
                openTime = DateUtil.plusDays(DateUtil.now(), -7);
            }
        } else {
            publishAt = publishAt * 1000L;
            //转时间
            openTime = new Date(publishAt);
        }
        return openTime;
    }

    /**
     * 获取交易签名
     * @param fromCredentials
     * @param nonce
     * @param tokenAddress
     * @param dataModel
     * @return
     */
    public static String getChainSign(OklinkChainEnum oklinkChainEnum, Credentials fromCredentials, BigInteger nonce, String tokenAddress, BigInteger value, BigInteger gasPrice, BigInteger gas, String data) {

        gas=gas.multiply(BigInteger.valueOf(oklinkChainEnum.getGas()));

        //封装交易基本参数
        RawTransaction rawTransaction = RawTransaction.createTransaction(
                nonce,
                gasPrice,
                gas,//2倍
                tokenAddress,
                value,
                data);
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction,oklinkChainEnum.getChainId(), fromCredentials);
        String signedData = Numeric.toHexString(signedMessage);
        if(Func.isEmpty(signedData)){
            throw new ServiceException("签名为空");
        }
        return signedData;

    }
    /**
     *       RawTransaction rawTransaction = RawTransaction.createTransaction(
     *                     nonce,
     *                     gasPrice,
     *                     gas.multiply(BigInteger.valueOf(2)),//2倍
     *                     tokenAddress,
     *                     BigInteger.ZERO,
     *                     data);
     *             byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, fromCredentials);
     *             String signedData = Numeric.toHexString(signedMessage);
     */
}
